package cn.bdqn.service.impl;

import cn.bdqn.util.MD5Utils;
import cn.bdqn.pojo.ItripUser;
import cn.bdqn.service.TokenService;
import com.alibaba.fastjson.JSON;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedisTemplate redisTemplate;


    /**
     * token:PC-userCode-userID-date-random(6)
     * @param userAgent
     * @param itripUser
     * @return
     */
    @Override
    public String getToken(String userAgent, ItripUser itripUser) {
        StringBuilder sb=new StringBuilder();
        sb.append("token:");
        UserAgent agent=UserAgent.parseUserAgentString(userAgent);
        if(agent.getOperatingSystem().isMobileDevice()){
            sb.append("mobel");
        }else{
            sb.append("PC");
        }
        sb.append("-"+ MD5Utils.getMD5(itripUser.getUserCode(),16));
        sb.append("-"+itripUser.getId().toString());
        sb.append("-"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        sb.append("-"+ MD5Utils.getMD5(userAgent,6));
        return sb.toString();
    }

    //保存token
    @Override
    public void save(String token,ItripUser itripUser) {
        if(token.startsWith("token:PC")){
            stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(itripUser), 2, TimeUnit.HOURS);
        }else{
            stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(itripUser));
        }
    }

    @Override
    public boolean validaty(String agent, String token) {
        if(stringRedisTemplate.opsForValue().get(token)==null){
            return false;
        }
        if(!token.split("-")[4].equals(MD5Utils.getMD5(agent,6))){
            return false;
        }
        return true;
    }

    @Override
    public boolean deleteToken(String token) {
      try{
          stringRedisTemplate.delete(token);
          return true;
      }catch (Exception e){
          return false;
      }
    }

    private long  protectTime=30*60;
    private long deleyTime=2*60;
    @Override
    public String reload(String agent, String token) throws Exception {
        if(this.validaty(agent,token)){
            String  createDate=token.split("-")[3];
            long time= Calendar.getInstance().getTimeInMillis()-new SimpleDateFormat("yyyyMMddHHmmss").parse(createDate).getTime();
            if(time<protectTime*1000){
                throw new Exception("token在保护期间");
            }
            ItripUser itripUser=JSON.parseObject(stringRedisTemplate.opsForValue().get(token),ItripUser.class);
            String newToken=this.getToken(agent,itripUser);
            this.save(newToken,itripUser);
            stringRedisTemplate.opsForValue().set(token,JSON.toJSONString(itripUser),deleyTime,TimeUnit.SECONDS);
            return  newToken;
        }else{
            throw new Exception("token不存在");
        }
    }
}
